package com.caigou.modules.info.ui.myself

import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.launcher.ARouter
import com.caigou.comm.base.bean.AppBackgroundInfo
import com.caigou.comm.base.constants.AppConstants
import com.caigou.comm.base.constants.RouterPath
import com.caigou.comm.base.container.BaseFragment
import com.caigou.comm.base.ext.Resource
import com.caigou.comm.base.ext.observe
import com.caigou.comm.base.ext.showToast
import com.caigou.comm.base.widget.SpaceItemDecoration
import com.caigou.modules.info.R
import com.caigou.modules.info.adapter.MyCollectedItemAdapter
import com.caigou.modules.info.bean.InfoBean
import com.caigou.modules.info.bean.InfoItemBean
import com.caigou.modules.info.databinding.FragmentMyCollectedBinding
import com.caigou.modules.info.viewmodel.MyInfoViewModel
import dagger.hilt.android.AndroidEntryPoint

/**
 * @author #Suyghur.
 * Created on 2021/11/20
 */
@AndroidEntryPoint
class MyCollectedFragment : BaseFragment() {

    private var _binding: FragmentMyCollectedBinding? = null
    private val binding get() = _binding!!

    private val myInfoViewModel: MyInfoViewModel by viewModels()
    private var page = 1
    private val limit = 10
    private var totalPage = 0

    private val items: MutableList<InfoItemBean> by lazy {
        mutableListOf()
    }

    private val recyclerViewItemDecoration by lazy {
        SpaceItemDecoration(requireActivity())
    }

    private val linearLayoutManager: LinearLayoutManager by lazy {
        LinearLayoutManager(requireActivity())
    }

    private val mAdapter: MyCollectedItemAdapter by lazy {
        MyCollectedItemAdapter(mutableListOf())
    }


    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        _binding = FragmentMyCollectedBinding.inflate(inflater, container, false)
        return _binding?.root
    }

    override fun initView() {
        binding.myCollectedSwipeRefreshLayout.run {
            setColorSchemeColors(resources.getColor(R.color.caigou_theme_color))
            setOnRefreshListener {
                mAdapter.loadMoreModule.isEnableLoadMore = false
                page = 1
                myInfoViewModel.getMyCollectedList(page, limit, AppBackgroundInfo.instance.userBean!!.userId)
            }
        }

        mAdapter.loadMoreModule.run {
            setOnLoadMoreListener {
                mAdapter.loadMoreModule.isEnableLoadMore = true
                myInfoViewModel.getMyCollectedList(page, limit, AppBackgroundInfo.instance.userBean!!.userId)
            }
            isAutoLoadMore = true
            isEnableLoadMoreIfNotFullPage = false
        }
        mAdapter.setOnItemClickListener { adapter, view, position ->
            ARouter.getInstance().build(RouterPath.Article.PAGE_ARTICLE)
                .withObject(AppConstants.ARTICLE_ITEM_BEAN, items[position])
                .navigation()
        }
        binding.myCollectedRecyclerView.run {
            layoutManager = linearLayoutManager
            adapter = mAdapter
            itemAnimator = DefaultItemAnimator()
            addItemDecoration(recyclerViewItemDecoration)
        }
    }

    override fun lazyLoad() {
        myInfoViewModel.getMyCollectedList(page, limit, AppBackgroundInfo.instance.userBean!!.userId)
    }

    override fun onBack() {
    }

    override fun observeViewModel() {
        observe(myInfoViewModel.myCollectedListLiveData, ::handleGetMyCollectedList)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    private fun handleGetMyCollectedList(result: Resource<InfoBean>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                binding.myCollectedSwipeRefreshLayout.isRefreshing = false
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("获取已收藏信息异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                binding.myCollectedSwipeRefreshLayout.isRefreshing = false
                mAdapter.loadMoreModule.isEnableLoadMore = true

                if (result.data == null) {
                    binding.myCollectedDetailLlEmpty.visibility = View.VISIBLE
                    binding.myCollectedRecyclerView.visibility = View.GONE
                    return
                }

                if (result.data!!.list.isNullOrEmpty()) {
                    binding.myCollectedDetailLlEmpty.visibility = View.VISIBLE
                    binding.myCollectedRecyclerView.visibility = View.GONE
                } else {
                    binding.myCollectedDetailLlEmpty.visibility = View.GONE
                    binding.myCollectedRecyclerView.visibility = View.VISIBLE
                }

                totalPage = result.data!!.totalPage

                if (page == 1) {
                    items.clear()
                    mAdapter.setList(result.data!!.list)
                } else {
                    mAdapter.addData(result.data!!.list)
                }
                items.addAll(result.data!!.list)

                if (result.data!!.pageSize < limit) {
                    mAdapter.loadMoreModule.loadMoreEnd(false)
                } else {
                    mAdapter.loadMoreModule.loadMoreComplete()
                }

                if (page >= totalPage) {
                    mAdapter.loadMoreModule.loadMoreEnd(false)
                } else {
                    page++
                }
            }
        }
    }
}